<template>
  <div>
    <div class="sectionCard" v-for="(item) in groups">
      <el-form label-position="left" :inline="true" label-width="100px">
        <div class="sectionTitle">{{ item.title }}</div>

        <el-row v-for="(child_item) in item.child">
          <el-form-item :label="child_item.label">
            <el-select v-if="child_item.type==2" v-model="child_item.value" style="width: 200px">
              <el-option
                  v-for="item_c in child_item.option"
                  :key="item_c.value"
                  :label="item_c.label"
                  :value="item_c.value"
              ></el-option>
            </el-select>
            <el-input v-else
                      :type="child_item.value_type=='number'?'number':'text'"
                      style="width: 200px"
                      clearable
                      v-model="child_item.value"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="publish(item.topic,child_item.key,child_item.value,child_item.value_type)">
              下发指令
            </el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>


</template>

<script setup>
import axios from "axios";
import {onMounted, ref} from "vue";
import MQTT from "../../mqtt/Mqtt";

let PublicMqtt = null;
/**
 * topic mqtt主题
 * title 组名称
 * value_type boolean，number,string
 * option 下拉框的下拉列表
 */
let groups = ref([{
  topic: 'aa',
  title: '组1',
  child: [
    {label: 'sf', type: '1', key: 'ccc', value: '', value_type: 'number'},
    {
      label: 'assf',
      type: '2',
      key: 'aaa',
      value: true,
      value_type: 'boolean',
      option: [{label: '启动', value: true}, {label: '停止', value: false}]
    }]
},
  {
    topic: 'aa',
    title: '组2',
    child: [{label: 'sf', type: '1', key: 'bbbb', value: '', value_type: ''}]
  }
])

function publish(topic, key,value,valueType) {
  if(valueType=='boolean'||valueType=='number'){
    try {
      value = JSON.parse(value)
    }catch (e){
      console.error('..........数据转换失败，异常信息',e)
      return ;
    }
  }
  let message = {key:value};
  PublicMqtt.publish(topic, JSON.stringify(message))
}

onMounted(() => {
  axios.get('/config.json').then((res) => {
    const config = res.data;
    console.log('......config', config)
    PublicMqtt = new MQTT(config);//创建连接
    PublicMqtt.init();//初始化mqtt
  })


})

</script>

<style lang="scss" scoped>

</style>